// src/books/book.service.ts
import { Injectable, NotFoundException } from '@nestjs/common';
import { Book, BookCreateDto, BookUpdateDto } from '../dto/book.dto';

@Injectable()
export class BookService {
  private books: Book[] = [
    {
      id: '1',
      title: 'JavaScript高级程序设计',
      author: 'Nicholas C. Zakas',
      publishYear: 2020,
      isbn: '978-7-115-53869-9',
      createTime: '2023-01-01T10:00:00Z',
      updateTime: '2023-01-01T10:00:00Z'
    },
    {
      id: '2',
      title: '深入理解TypeScript',
      author: 'Basarat Ali Syed',
      publishYear: 2021,
      isbn: '978-7-121-41234-5',
      createTime: '2023-01-02T10:00:00Z',
      updateTime: '2023-01-02T10:00:00Z'
    }
  ];

  // 获取所有图书
  getAllBooks(): Book[] {
    return this.books;
  }

  // 根据ID获取图书
  getBookById(id: string): Book {
    const book = this.books.find(book => book.id === id);
    if (!book) {
      throw new NotFoundException(`图书ID为 ${id} 的图书不存在`);
    }
    return book;
  }

  // 创建新图书
  createBook(bookData: BookCreateDto): Book {
    const newBook: Book = {
      id: this.generateId(),
      ...bookData,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    };
    
    this.books.push(newBook);
    return newBook;
  }

  // 更新图书信息
  updateBook(id: string, updateData: BookUpdateDto): Book {
    const bookIndex = this.books.findIndex(book => book.id === id);
    
    if (bookIndex === -1) {
      throw new NotFoundException(`图书ID为 ${id} 的图书不存在`);
    }

    this.books[bookIndex] = {
      ...this.books[bookIndex],
      ...updateData,
      updateTime: new Date().toISOString()
    };

    return this.books[bookIndex];
  }

  // 删除图书
  deleteBook(id: string): void {
    const bookIndex = this.books.findIndex(book => book.id === id);
    
    if (bookIndex === -1) {
      throw new NotFoundException(`图书ID为 ${id} 的图书不存在`);
    }

    this.books.splice(bookIndex, 1);
  }

  // 生成唯一ID
  private generateId(): string {
    return Date.now().toString() + Math.random().toString(36).substr(2, 9);
  }
}